import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Login from '@/views/Login/index.vue'
import { userInfoApi } from '@/http/api'
import { useUser } from '@/store/user'
import { ElMessage } from 'element-plus'

const routes: RouteRecordRaw[] = [
    {
        path: "/login", component: Login
    },
    {
        path: "/",
        redirect: '/index'
    },
    {
        path: "/",
        component: () => import("../views/home/index.vue"),
        children: [{ path: 'index', component: () => import('@/views/Index/index.vue') }],
    },
    // {
    //     path: "/ums",
    //     component: () => import("../views/home/index.vue"),
    //     children: [{ path: 'admin', component: Login }],
    // },
]






const router = createRouter({
    routes,
    history: createWebHashHistory(),
});

router.beforeEach((to, from, next) => {
    const store = useUser()
    let token = localStorage.getItem("token")
    if (store.menus.length === 0 && token) {
        userInfoApi().then((res) => {
            if (res.code === 200) {
                // console.log(res.data.menus);
                store.menus = res.data.menus
                store.username = res.data.username
                store.routes.forEach((p) => {
                    // 动态路由的对象
                    const route: RouteRecordRaw = {
                        path: `/${p.name}`,
                        name: p.name,
                        meta: { title: p.title },
                        component: () => import("../views/home/index.vue"),

                        children: p.children.map(item => ({
                            path: item.name,
                            meta: { title: item.title },
                            component: () => import(`../views/${p.name}/${item.name}.vue`),
                        })),
                    }
                    // 判断,给创建完的动态路由的对象添加重定向
                    if (p.children[0]) {
                        route.redirect = `/${p.name}/${p.children[0]?.name}`;
                    }
                    // 创建动态路由
                    router.addRoute(route)
                })

                next(to.fullPath);
            }
        })
    } else if (!token && to.path !== '/login') {
        ElMessage.error("请先登录")
        next('/login');
    } else if (token && to.path === '/login' && store.menus.length !== 0) {

        next(from.fullPath);
    } else {
        next();
    }


})

export default router